package Test1;

import java.io.IOException;

public class IO {

    public static void main(String[] args) throws IOException {

        Desk desk = new Desk();
        Foodie f = new Foodie(desk);
        Cooker c = new Cooker(desk);

        c.start();
        f.start();

    }

}

class Cooker extends Thread {

    private Desk desk;

    public Cooker(Desk desk) {
        this.desk = desk;
    }

    @Override
    public void run() {

        while (true) {
            synchronized (desk.getObj()) {

                if (desk.getCount() == 0) {
                    break;
                } else {
                    if (!desk.isFlag()) {
                        System.out.println("厨师正在做餐！剩余餐数" + desk.getCount());
                        desk.setFlag(true);
                        desk.getObj().notifyAll();
                    } else {
                        try {
                            desk.getObj().wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}

class Foodie extends Thread {

    private Desk desk;

    public Foodie(Desk desk) {
        this.desk = desk;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (desk.getObj()) {
                if (desk.getCount() == 0) {
                    break;
                } else {
                    if (desk.isFlag()) {
                        System.out.println("客人正在吃!");
                        desk.setFlag(false);
                        desk.getObj().notifyAll();
                        desk.setCount(desk.getCount() - 1);
                    } else {
                        try {
                            desk.getObj().wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }
    }
}

class Desk {

    private boolean flag = false;

    private int count = 10;

    private final Object obj = new Object();

    public Desk() {
    }

    public Desk(boolean flag, int count) {
        this.flag = flag;
        this.count = count;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public Object getObj() {
        return obj;
    }
}